<template>
    <div class="title">
        <div class="input">
            <h1>登录</h1>
            <div class="inputs" v-if="!phone">
                <div style="position: relative;margin: 3.5vh auto;  height: 35%; width: 70%;">
                    <input type="text" v-model="use" class="text" required>
                    <div class="user">user</div>
                </div>
                <div style="position: relative;margin: 3.5vh auto; height: 35%; width: 70%;">
                    <input type="password" v-model="password" class="text" required>
                    <div class="user">password</div>
                </div>
                <div class="login">
                    <el-button type="primary" @click="login">登录</el-button>
                </div>
            </div>
            <div class="inputs phoneInput" v-else>
                <el-form :model="form" label-width="100px" label-position="right" ref="ruleFormRef" :rules="rules">
                    <el-form-item prop="phone" label="输入手机号">
                        <el-input placeholder="请输入手机验证码手机号" v-model="form.phone" type="text" />
                    </el-form-item>
                    <el-form-item label="图片验证码" prop="imageCode">
                        <el-input style="width: 40%;" placeholder="请输入图片验证码" v-model="form.imageCode" type="text" />
                        <div class="imageCode">
                            <span @click="cut" v-if="imageCode">看不清,换一张</span>
                            <span @click="cut" v-else>获取图片验证码</span>
                            <img v-if="imageCode" :src="imageCode" alt="" />
                        </div>
                    </el-form-item>
                    <el-form-item label="短信验证码" prop="phonecodeInput">
                        <el-input style="width: 70%;" placeholder="请输入手机短信验证码" v-model="form.phonecodeInput" type="text" />
                        <div class="cds ok" style="cursor: pointer;" @click="cd.down(getcodePhom)" v-if="controller">
                            获取验证码
                        </div>
                        <div class="cds error" v-else>
                            {{ cd.display.value + '秒后可重发' }}
                        </div>
                    </el-form-item>
                    <!-- 登录 -->

                    <div class="login">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            登录
                        </el-button>
                    </div>
                </el-form>
            </div>

            <span class="phone" @click="phone = !phone">{{ !phone ? "手机登录" : "密码登录" }} </span>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, type Ref } from "vue"
import { loginByAccount, getloginImg, getPhoneCode, Phonelogin } from '@/request/api'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import countDown from '@/hooks/countDown'
import { setlocalStorage } from '@/hooks/operationLocalStorage'
import { useRouter } from "vue-router"
import { useStore } from '@/stores/counter'
import Cookies from "js-cookie";
interface loignBtac {
    id: string
    password: string
}
interface getPhoneCode {
    imageCode: string;
    phone: string;

}
interface phonelogin {
    imageCode: string;
    phone: string;
    phoneCode: string;
}
const router = useRouter()
const store = useStore()


//账号密码登录
//收集账号密码
let use = ref<string>('')
let password = ref<string>('')
//是否切换手机登录
let phone = ref<boolean>(false)
//开始登录
let login = () => {
    loginByAccount<loignBtac>({ "id": use.value, "password": password.value }).then(res => {
        isLogin(res)
    })
}
//用于判断是否登录成功
const isLogin = (res: any) => {
    if (res.code) {
        ElMessage({
            showClose: true,
            message: `欢迎回来“${res.data.name}”`,
            type: 'success',
        })
        //将用户信息存储在pinia里面           
        // setlocalStorage("use", res.data)
        store.user = res.data
        //存储token
        setlocalStorage("token", res.data.token)
        setlocalStorage("refreshToken", res.data.refreshToken)
        use.value = ''
        password.value = ''
        router.push({
            path: '/home'
        })
    } else
        ElMessage({
            showClose: true,
            message: `${res.msg}`,
            type: 'error',
        })
}



//手机号登录逻辑
//表单数据收集
const form = reactive({
    phone: '',
    imageCode: '',
    phonecodeInput: ''
})
//获取图片验证码
const cut = () => {
    if(form.phone==''){
        return   ElMessage({
            showClose: true,
            message: `请先输入手机号`,
            type: 'error',
        })
    }
    getloginImg<string>(form.phone).then(res => {
        imageCode.value = 'data:image/png;base64,' + res.data
    })
}
// cut()
//表单校验
const ruleFormRef = ref<FormInstance>()
const validatePass = (rule: any, value: any, callback: any) => {
    //查看用户有无被注册过      
    var re = /^1((3[\d])|(4[5,6,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[1-3,5-8])|(9[1,8,9]))\d{8}$/
    if (re.test(value + '')) {
        callback();
    } else {
        callback(new Error('手机号不合法'));
    }
}
//校验条件
const rules = reactive({
    "phone": [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' },],
    "imageCode": { required: true, message: '验证码不能为空', trigger: 'blur' },
    "phonecodeInput": { required: true, message: '验证码不能为空', trigger: 'blur' }
})

//获取手机验证码
let controller = ref<boolean>(true)
let cd = new countDown(controller, 60)
//开始获取验证码
const getcodePhom = () => {
    getPhoneCode<getPhoneCode>({
        phone: form.phone,
        imageCode: form.imageCode,
    }).then(res => {
        if (!res.data) {
            cd.display.value = 60
            cd.controller.value=true
           
            clearInterval(cd.clear)
            cd.clear=null
            ElMessage({
                showClose: true,
                message: `${res.msg}`,
                type: 'error',
            })
        }
    })
}
//开始手机号登录
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //开始进行登录，服务端验证
            Phonelogin<phonelogin>({
                phone: form.phone,
                imageCode: form.imageCode,
                phoneCode: form.phonecodeInput
            }).then(res => {
                isLogin(res)

            })
        } else {

        }
    })
}
let imageCode = ref<string>('')
</script>

<style lang=less  scoped>
// :deep(.el-form-item__content) {
//     transform: translate(-40%, 0);
// }

.text {
    width: 100%;
    border: solid 1px rgb(139, 139, 139);
    outline: none;
    height: 90%;
    color: #000;
    border-radius: 5px;
    font-size: 2vh;
    margin: 0px auto;
    display: block;
    z-index: 2;
    top: 20px;
    background-color: rgba(240, 248, 255, 0);
}

.phoneInput {
    padding: 2vh 2vw;

    .login {
        margin-top: 6vh;
    }
}

.login {
    width: 100%;

}

.text:focus~.user,
.text:valid~.user {
    transform: translateY(-50%) scale(0.75);
    background-color: #e7e0e3;

    z-index: 10;
    color: rgb(15, 122, 122);

}

.user {
    top: 0px;
    margin-left: 10px;
    // width: 6vw;
    text-align: center;
    // background-color: #a1a1a1;
    height: 90%;
    .flexSa();
    justify-content: flex-start;
    align-items: center;
    color: #000;
    font-size: 4vh;
    z-index: 1;

    position: absolute;
    transition: all 0.4s ease-in-out;

}



.title {
    width: 30vw;
    .flexSa();
    align-items: center;
    height: 50vh;
    z-index: 10000;
    position: absolute;
    background-color: #e7e0e3;
    opacity: 0.9;
    right: 2%;
    border: 1px solid rgba(153, 146, 146, 0.267);
    top: 15%;
    border-radius: 2vw;
    backdrop-filter: blur(10px);

    .cds {
        width: 29%;
        margin-left: 1%;
        height: 100%;
        border-radius: 30px;
        .textNOLine();
    }

    .ok {
        color: #fff;
        background-color: #409EFF;
    }

    .error {
        color: #fff;
        background-color: rgb(177, 177, 177);
    }

    .imageCode {
        .flexAc();
        font-size: 5px;
        color: #000;
        width: 55%;
        justify-content: space-between;
        margin-left: 2%;

        img {
            height: 1.5vw;
            margin-left: 10px;
            aspect-ratio: 4/1;
        }

        span {
            .textNOLine();
            cursor: pointer;
            display: inline-block;
        }
    }

    .inputs {
        height: 50%;
    }



    .input {
        // .flexSa();
        flex-wrap: wrap;
        width: 100%;
        text-align: center;
        margin: 0px auto;
        height: 100%;
        aspect-ratio: 1/1;
        background-color: #f0e3e8;
        opacity: 1;
        color: #000 !important;

        border-radius: 2vw;
        box-shadow: 2px 3px 7px rgba(0, 0, 0, 0.493)
    }
}

h1 {
    width: 100%;
    margin-top: 5vh;
    text-align: center;
}

.phone {
    font-size: 10px;
    text-align: right;
    cursor: pointer;
    margin-right: 10%;
    height: 10%;
    overflow: hidden;
    display: inline-block;
    position: absolute;
    right: 5%;
    color: #000;
}

.phone::after,
.imageCode span::after {
    content: ' ';
    display: block;
    height: 1px;
    background-color: #000;
    transition: all 0.3s ease-in-out;
    transform: scale(0);
    transform-origin: left;

}

.imageCode span:hover::after {
    transform: scale(1);
}

.phone:hover::after {
    transform: scale(1);
}
</style>